﻿using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace System.Net.Http
{
	/// <summary>
	/// Provides a proxy class to HttpClient for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.
	/// </summary>
	public class HttpClientProxy : IHttpClient, IDisposable
	{
		readonly HttpClient _httpClient;
		bool _disposed;

		/// <summary>
		/// Initializes a new instance of the HttpClient class.
		/// </summary>
		public HttpClientProxy()
		{
			_httpClient = new HttpClient();
		}

		/// <summary>
		/// Initializes a new instance of the HttpClient class with a specific handler.
		/// </summary>
		/// <param name="handler">The HTTP handler stack to use for sending requests.</param>
		public HttpClientProxy(HttpMessageHandler handler)
		{
			_httpClient = new HttpClient(handler);
		}

		/// <summary>
		/// Gets or sets the base address of Uniform Resource Identifier (URI) of the Internet resource used when sending requests.
		/// </summary>
		public Uri BaseAddress
		{
			get
			{
				return _httpClient.BaseAddress;
			}
			set
			{
				_httpClient.BaseAddress = value;
			}
		}

		/// <summary>
		/// Gets the headers which should be sent with each request.
		/// </summary>
		public HttpRequestHeaders DefaultRequestHeaders
		{
			get 
			{
				return _httpClient.DefaultRequestHeaders;
			}
		}

		/// <summary>
		/// Send a GET request to the specified Uri as an asynchronous operation.
		/// </summary>
		/// <param name="requestUri">The Uri the request is sent to</param>
		/// <returns>The task object representing the asynchronous operation.</returns>
		public Task<HttpResponseMessage> GetAsync(Uri requestUri)
		{
			return _httpClient.GetAsync(requestUri);
		}

		/// <summary>
		/// Releases the unmanaged resources and disposes of the managed resources used by the HttpClientProxy.
		/// Cleans up the undelying <see cref="HttpClient"/>.
		/// </summary>
		public void Dispose()
		{
			Dispose(true);

			GC.SuppressFinalize(this);
		}

		protected virtual void Dispose(bool disposing)
		{
			if (_disposed == false)
			{
				if (disposing)
				{
					if (_httpClient != null)
					{
						_httpClient.Dispose();
					}
				}

				_disposed = true;
			}
		}
	}
}
